<script setup>
import "ol/ol.css"
import Map from 'ol/Map.js';
import {Feature, View} from "ol";
import {onMounted} from "vue";
import getTDTLayer from "@/js/UseTDT2305.js";
import {registerCGCS2000} from "@/js/UseTDT2305.js";
import VectorLayer from "ol/layer/Vector.js";
import VectorSource from "ol/source/Vector.js";
import {GeoJSON, WFS} from "ol/format.js";
import {Draw, Modify,Select} from "ol/interaction.js";

registerCGCS2000()
const tdt_ter = getTDTLayer('地形晕渲','球面墨卡托投影','d06c497b107f57ebd6a0f8fbf967292d')

const typeMap = {
  point: 'city',
  line: 'rai_4m',
  polygon: 'bou2_4p',
  Point: 'city',
  LineString: 'rai_4m',
  Polygon: 'bou2_4p',
  MultiPoint: 'city',
  MultiLineString: 'rai_4m',
  MultiPolygon: 'bou2_4p'
}


const vectorLayer = new VectorLayer()
let map
const initMap = () => {
 map = new Map({
    target: 'map',
    layers: [tdt_ter],
    view: new View({
      center: [12926818.776678564, 2793810.2689550915],
      zoom: 3,
      projection: 'EPSG:3857'
    })
  })
}
onMounted(initMap)
let draw

const addFeature = (type) => {
  vectorLayer.setSource(null)
  if(!map.getLayers().getArray().includes(vectorLayer)){
    map.addLayer(vectorLayer)
  }

  const vectorSource = new VectorSource({
    format: new GeoJSON({
      geometryName: 'geom',
    }),
    url: `http://localhost:8080/geoserver/webgis2305/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=webgis2305%3A${typeMap[type]}&outputFormat=application%2Fjson`
  })
  vectorLayer.setSource(vectorSource)

  if(map.getInteractions().getArray().includes(draw)){
    map.removeInteraction(draw)
    draw = null
  }

  vectorSource.once('featuresloadend',()=>{
    let sourceType = vectorLayer.getSource().getFeatures()[0].getGeometry().getType()
    console.log(sourceType)
    draw = new Draw({
      source: vectorSource,
      type: sourceType
    })
    map.addInteraction(draw)

    draw.on('drawend',(evt)=>{
      const newGeometry = evt.feature.getGeometry().clone()
      const newFeature = new Feature()
      newFeature.setGeometryName('geom')
      newFeature.setGeometry(newGeometry)
      wfsRequest(newFeature,'insert',type)
    })
  })

}

const ModifyFeature = () => {
  if(map.getInteractions().getArray().includes(draw)){
    map.removeInteraction(draw)
    draw = null
  }
  const select = new Select()
  map.addInteraction(select)
  const modify = new Modify({
    features: select.getFeatures(),
  })
  map.addInteraction(modify)
  modify.on('modifyend',(evt)=>{
    const sourceType = evt.features.item(0).getGeometry().getType()
    console.log(sourceType)
    wfsRequest(evt.features.item(0),'update',sourceType)
  })
}

const deleteFeature = () => {
  if(map.getInteractions().getArray().includes(draw)){
    map.removeInteraction(draw)
    draw = null
  }
  const select = new Select()
  map.addInteraction(select)
  select.on('select',(evt)=>{
    const selectedFeature = evt.selected[0]
    const sourceType = selectedFeature.getGeometry().getType()
    wfsRequest(selectedFeature,'delete',sourceType,)
  })
}

const wfsRequest = (newFeature,operation,type) => {
  const options = {
    featureNS:'www.webgis2305.com',
    featurePrefix:'webgis2305',
    featureType:typeMap[type],
    srsName: 'EPSG:3857'
  }
  let wfsTranaction
  switch (operation){
    case 'insert':
      wfsTranaction = new WFS().writeTransaction([newFeature],null,null,options)
      break;
      case 'update':
      wfsTranaction = new WFS().writeTransaction(null,[newFeature],null,options)
      break;
      case 'delete':
      wfsTranaction = new WFS().writeTransaction(null,null,[newFeature],options)
      break;
  }

  const wfsString = new XMLSerializer().serializeToString(wfsTranaction)
  const xhr = new XMLHttpRequest()
  xhr.open('POST', 'http://localhost:8080/geoserver/webgis2305/ows?service=WFS', true)
  xhr.setRequestHeader('Content-Type', 'text/xml')
  xhr.send(wfsString)

  xhr.onreadystatechange = function (){
    if(xhr.status === 200 && xhr.readyState === 4){
      console.log('成功响应:', xhr.responseText);
    } else if (xhr.readyState === 4 && xhr.status !== 200) {
      console.error('WFS操作失败:', xhr.status, xhr.responseText);
    }
  }
}

</script>

<template>
  <div class="edittools">
    <button @click="addFeature('point')">添加点要素</button>
    <button @click="addFeature('line')">添加线要素</button>
    <button @click="addFeature('polygon')">添加面要素</button>
    <button @click="ModifyFeature">修改要素</button>
    <button @click="deleteFeature">删除要素</button>
  </div>
<div id="map"></div>
</template>

<style scoped>
#map{
  width: 100%;
  height: 700px;
}

.edittools{
  position: absolute;
  top:10px;
  left: 35px;
  z-index: 2;
  opacity: 0.5;
}

.edittools button{
  width: 75px;
  height: 30px;
}
</style>